package network.link;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

/**
 * Deframes an inputstream and output them as a sequence of byte[]s
 */

public class FrameInputStream {
  
  private final InputStream in_stream_;
  
  /**
   * Creates a frameinputstream that streams from stream.
   * @requires stream not null
   * @param stream Input Stream to stream from
   */
  
  public FrameInputStream(InputStream stream) {
    assert stream != null;
    in_stream_ = stream;
  }
  
  /**
   * Reads a package of data
   * @return a package of data read or null if end has been reached
   * @throws IOException
   */
  
  public byte[] read() throws IOException {
    Vector<Byte> ret = new Vector<Byte>();
    
    while (true) {
      int read_value = in_stream_.read();
      if (read_value == -1) {
        //done
        //System.out.println("Reading done here...");
        break;
      }
      byte in_byte = (byte)read_value;
      
      ret.add(in_byte);
      
      if (Frame.isTerminated(ret)) {
        break;
      } 
    }
    if (!Frame.isTerminated(ret)) {
      return null;
    }
    return Frame.unmarshall(ret);
  }
  
  public void close() {
    try {
      in_stream_.close();
    } catch (IOException e) {
      // TODO
      System.out.println("input stream failed to close");
    }
  }
  
}
